import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/login.vue'
import Home from '@/components/home.vue'
import Welcome from '@/components/welcome.vue'
import Users from '@/components/user/users.vue'
import Rights from '@/components/power/Rights.vue'
import Roles from '@/components/power/Roles.vue'
import Cate from '@/components/goods/Cate.vue'

Vue.use(VueRouter)

const routes = [
  // 路由表
  { path: '/', component: Login },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome', // 重定向到welcome
    // 子路由
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate }
    ]
  }
]

const router = new VueRouter({
  // 挂载路由表
  routes
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  // next() 放行 next（'/login')强制跳转
  // 如果是login 页面不检测
  if (to.path === '/login') return next()
  // 如果是其他页面，检测获取的token值
  const tokenstr = window.sessionStorage.getItem('token')
  // 没有token 跳转到登录页面
  if (!tokenstr) return next('/login')
  // 有token 继续正常访问
  next()
})
export default router
